import React, { FC, useMemo } from 'react'
import { connect } from 'react-redux';
import { RootState } from 'store';
import { Breadcrumb } from 'antd'
import { API } from 'App.d'
import { Link, useLocation, withRouter } from 'react-router-dom'

interface MyBreadCrumbProps {
  routes: Array<API.IRoute>
}

const MyBreadCrumb: FC<MyBreadCrumbProps> = (props) => {
  const { pathname: currentPath } = useLocation()

  const getPathnameArr = () => { // 通过地址获取当前路径的数组
    let pathnameArr: any = []
    pathnameArr.push(currentPath)//先添加一次
    let index = currentPath.lastIndexOf('/') //获取最后一个/的位置
    while (index !== -1 && index !== 0) { // 如果index不等于-1, 并且index不等于0, 则继续循环
      pathnameArr.unshift(currentPath.substring(0, index)) //添加到数组的开头
      index = currentPath.lastIndexOf('/', index - 1) // 将index设置为上一次的/的位置, 并且index-1
    }
    return pathnameArr //返回数组
  }



  const getFlattenRoutes = (routes: any) => { //拍平路由数组, 备用
    let newRoutes: any = [] //准备一个新数组
    routes.forEach((route: any) => {
      newRoutes.push(route) // 将当前路由放入新数组
      if (route.routes) { // 如果当前路由有子路由
        newRoutes = [...newRoutes, ...getFlattenRoutes(route.routes)] // 将子路由放入新数组
      }
    })
    return newRoutes // 返回新数组
  }

  const flattenRoutes = useMemo(() => getFlattenRoutes(props.routes), [props.routes])

  const renderBreadCrumb = () => {
    const pathnameArr = getPathnameArr() // 获取当前路径的数组

    return pathnameArr.map((pathname: any, index: number) => {
      const route = flattenRoutes.find((route: any) => route.path === pathname) // 找到每一级对应的路由
      if (route) {  // 如果有路由
        return ( // 返回面包屑
          <Breadcrumb.Item key={index}>
            {route.name}
          </Breadcrumb.Item>
        )
      }
    })
  }

  return (
    <div>
      <Breadcrumb separator=">">
        <Breadcrumb.Item >
          <Link to="/home">首页</Link>
        </Breadcrumb.Item>
        {renderBreadCrumb()}
      </Breadcrumb >
    </div>
  )
}

export default connect(
  (state: RootState) => ({ routes: state.user.routes }),
)(MyBreadCrumb)